<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用ID" prop="applicationId">
        <el-select v-model="queryParams.applicationId" placeholder="请选择应用ID" remote clearable filterable size="small" @change="searchFieldChanged('applicationId', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['applicationId']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模块名称" prop="moduleName">
        <el-select v-model="queryParams.moduleName" placeholder="请选择模块名称" remote clearable filterable size="small" @change="searchFieldChanged('moduleName', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['moduleName']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模块描述" prop="moduleDescription">
        <el-select v-model="queryParams.moduleDescription" placeholder="请选择模块描述" remote clearable filterable size="small" @change="searchFieldChanged('moduleDescription', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['moduleDescription']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序编号" prop="orderNum">
        <el-select v-model="queryParams.orderNum" placeholder="请选择排序编号" remote clearable filterable size="small" @change="searchFieldChanged('orderNum', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['orderNum']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模块前缀" prop="modulePrefix">
        <el-select v-model="queryParams.modulePrefix" placeholder="请选择模块前缀" remote clearable filterable size="small" @change="searchFieldChanged('modulePrefix', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['modulePrefix']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="包路径" prop="packageName">
        <el-select v-model="queryParams.packageName" placeholder="请选择包路径" remote clearable filterable size="small" @change="searchFieldChanged('packageName', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['packageName']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-select v-model="queryParams.author" placeholder="请选择作者" remote clearable filterable size="small" @change="searchFieldChanged('author', $event)">
          <el-option
            v-for="dict in pageModelConfig.searchColumnsOptions['author']"
            :key="dict.key"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 头部工具条 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['codegen:module:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['codegen:module:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['codegen:module:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['codegen:module:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主要列表 -->
    <el-table v-loading="loading" :data="moduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="42" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="应用ID" align="center" prop="applicationId" />
      <el-table-column label="模块名称" align="center" prop="moduleName" />
      <el-table-column label="模块描述" align="center" prop="moduleDescription" />
      <el-table-column label="排序编号" align="center" prop="orderNum" />
      <el-table-column label="模块前缀" align="center" prop="modulePrefix" />
      <el-table-column label="包路径" align="center" prop="packageName" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['codegen:module:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['codegen:module:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看、添加、修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="应用ID" prop="applicationId">
          <el-input v-model="form.applicationId" placeholder="请输入应用ID" />
        </el-form-item>
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="模块描述" prop="moduleDescription">
          <el-input v-model="form.moduleDescription" placeholder="请输入模块描述" />
        </el-form-item>
        <el-form-item label="排序编号" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序编号" />
        </el-form-item>
        <el-form-item label="模块前缀" prop="modulePrefix">
          <el-input v-model="form.modulePrefix" placeholder="请输入模块前缀" />
        </el-form-item>
        <el-form-item label="包路径" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入包路径" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.addSupport" /> 是否添加不存在的数据
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
            <el-checkbox v-model="upload.removeSupport" /> 是否删除导入列表中没有的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { searchChanged, listModule, getModule, delModule, addModule, updateModule } from "@/api/tool/gen/module";
import { getToken } from "@/utils/auth";

export default {
  name: "Module",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模块表格数据
      moduleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 页面模型配置
      pageModelConfig: {
        name: "module",
        label: "模块",
        labelWidth: "100px",
        searchColumns: [
          { key: "id", label: "id", align: "center", prop: "id", visible: false, showOverflowTooltip: true },
          { key: "applicationId", label: "应用ID", align: "center", prop: "applicationId", visible: true, showOverflowTooltip: true },
          { key: "moduleName", label: "模块名称", align: "center", prop: "moduleName", visible: true, showOverflowTooltip: true },
          { key: "moduleDescription", label: "模块描述", align: "center", prop: "moduleDescription", visible: true, showOverflowTooltip: true },
          { key: "orderNum", label: "排序编号", align: "center", prop: "orderNum", visible: true, showOverflowTooltip: true },
          { key: "modulePrefix", label: "模块前缀", align: "center", prop: "modulePrefix", visible: true, showOverflowTooltip: true },
          { key: "packageName", label: "包路径", align: "center", prop: "packageName", visible: true, showOverflowTooltip: true },
          { key: "author", label: "作者", align: "center", prop: "author", visible: true, showOverflowTooltip: true },
        ],
        searchColumnsOptions: {
        },
        columns: [
          { key: "id", label: "id", align: "center", prop: "id", visible: false, showOverflowTooltip: true },

          { key: "applicationId", label: "应用ID", align: "center", prop: "applicationId", visible: true, showOverflowTooltip: true },

          { key: "moduleName", label: "模块名称", align: "center", prop: "moduleName", visible: true, showOverflowTooltip: true },

          { key: "moduleDescription", label: "模块描述", align: "center", prop: "moduleDescription", visible: true, showOverflowTooltip: true },

          { key: "orderNum", label: "排序编号", align: "center", prop: "orderNum", visible: true, showOverflowTooltip: true },

          { key: "modulePrefix", label: "模块前缀", align: "center", prop: "modulePrefix", visible: true, showOverflowTooltip: true },

          { key: "packageName", label: "包路径", align: "center", prop: "packageName", visible: true, showOverflowTooltip: true },

          { key: "author", label: "作者", align: "center", prop: "author", visible: true, showOverflowTooltip: true },

        ],
        columnsOptions: {
        }
      },
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationId: null,
        moduleName: null,
        moduleDescription: null,
        orderNum: null,
        modulePrefix: null,
        packageName: null,
        author: null,
        params: {
          changedField: null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applicationId: [
          { required: true, message: "应用ID不能为空", trigger: "blur" }
        ],
        moduleName: [
          { required: true, message: "模块名称不能为空", trigger: "blur" }
        ],
      },
      // 数据导入参数
      upload: {
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否添加不经存在的数据
        addSupport: 0,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 是否删除导入列表中没有的数据
        removeSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: import.meta.env.VUE_APP_BASE_API + "/codeGen/module/importData"
      }
    };
  },
  created() {
    // 收集查询参数，默认均以 params 下的通用参数方式提交
    Object.keys(this.$route.query).forEach(key => {
      let have = false;
      Object.keys(this.queryParams).forEach(objKey => {
        if (key === objKey) {
          have = true;
        }
      });
      if(have){
        if(key==='pageNum'||key==='pageSize'){
          this.queryParams[key] = Number(this.$route.query[key]);
        }else{
          this.queryParams[key] = this.$route.query[key];
        }
      }else{
        this.queryParams.params[key] = this.$route.query[key];
      }
    });
    // 初始化搜索字段
    this.searchFieldChanged();
  },
  methods: {
    // 搜索字段改变
    searchFieldChanged(changedField, value) {
      this.queryParams.params.width = window.innerWidth;
      this.queryParams.params.height = window.innerHeight;

      let queryParams = this.addDateRange(this.queryParams, this.dateRange);
      queryParams.params.changedField = changedField;
      searchChanged(this.queryParams).then(res => {
        if(res.searchColumns){
          this.pageModelConfig.searchColumns = res.searchColumns;
          for (let obj of this.pageModelConfig.searchColumns) {
            this.pageModelConfig.searchColumnsOptions[obj.key] = obj.selectOptions;
          }
        }
        if(res.searchColumnOptions){
          this.pageModelConfig.searchColumnsOptions = res.searchColumnOptions;
        }

        // 如果检索条件验证通过，刷新列表
        if(res.data.params.searchValid){
          this.getList();
        } else {
          this.getList();
        }
      });
      if ((changedField === 'pageNum' || changedField === 'pageSize') && value) {
        let param = {applicationId: value};
        const query = { ...this.$route.query, ...param };
        this.$router.replace({ path: this.$route.path, query });
      }
    },
    /** 查询模块列表 */
    getList() {
      this.loading = true;
      listModule(this.queryParams).then(response => {
        this.moduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicationId: null,
        moduleName: null,
        moduleDescription: null,
        orderNum: null,
        modulePrefix: null,
        packageName: null,
        author: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模块";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getModule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模块";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateModule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模块编号为"' + ids + '"的数据项？').then(function() {
        return delModule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/codeGen/module/export', {
        ...this.queryParams
      }, `module_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/codeGen/module/importTemplate', {
      }, `module_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
